import random
import string
from app.settings import settings
import os
from qcloud_cos import CosConfig, CosS3Client
from qcloud_cos.cos_exception import CosClientError, CosServiceError
from fastapi import UploadFile

# 初始化 COS 客户端
config = CosConfig(Region=settings.COS_REGION, SecretId=settings.COS_SECRET_ID, SecretKey=settings.COS_SECRET_KEY)
cos_client = CosS3Client(config)

# 允许的文件类型
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

async def upload_image(file: UploadFile, path: str):
    path = f"upload/{path}"
    if file.filename == '':
        return False
    if not allowed_file(file.filename):
        return False
    # 生成随机文件名
    extension = file.filename.rsplit('.', 1)[1].lower()
    random_filename = generate_random_filename(extension)
    # 在腾讯云 COS 中的存储路径
    cos_key = f"{path}/{random_filename}"
    try:
        # 上传文件到 COS
        response = cos_client.put_object(
            Bucket=settings.COS_BUCKET,
            Key=cos_key,
            Body=file.file,
        )
        # 生成文件的访问 URL
        file_url = f"https://{settings.COS_BUCKET}.cos.{settings.COS_REGION}.myqcloud.com/{cos_key}"
        return file_url
    except CosClientError as e:
        print(f"客户端错误: {e}")
        return False
    except CosServiceError as e:
        print(f"服务器错误: {e}")
        return False


def generate_random_filename(extension):
    random_str = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
    return f"{random_str}.{extension}"

def allowed_file(filename):
    ret = '.' in filename and filename.rsplit('.', 1)[1].lower() in settings.ALLOWED_IMAGES
    print(ret)
    return ret

def allowed_files(filename):
    ret = '.' in filename and filename.rsplit('.', 1)[1].lower() in settings.ALLOWED_EXTENSIONS
    print(ret)
    return ret
#
# async def upload_file(file,path):
#     if file.filename == '':
#         return False
#     if allowed_files(file.filename):
#         extension = file.filename.rsplit('.', 1)[1].lower()
#         random_filename = generate_random_filename(extension)
#         url = os.path.join(settings.UPLOAD_FOLDER+"/"+path, random_filename)
#     else:
#         return False
#     with open(url, "wb") as f:
#         f.write(file.file.read())
#     url = url.replace('\\', '/')
#     return settings.APP_IP+url

async def upload_file(file: UploadFile, path: str):
    path = f"upload/{path}"
    if file.filename == '':
        return False

    if not allowed_files(file.filename):
        return False

    # 生成随机文件名
    extension = file.filename.rsplit('.', 1)[1].lower()
    random_filename = generate_random_filename(extension)

    # 在 COS 中的存储路径
    cos_key = f"{path}/{random_filename}"

    try:
        # 上传文件到 COS
        response = cos_client.put_object(
            Bucket=settings.COS_BUCKET,
            Key=cos_key,
            Body=file.file,
        )

        # 生成文件的访问 URL
        file_url = f"https://{settings.COS_BUCKET}.cos.{settings.COS_REGION}.myqcloud.com/{cos_key}"
        return file_url
    except CosClientError as e:
        print(f"客户端错误: {e}")
        return False
    except CosServiceError as e:
        print(f"服务器错误: {e}")
        return False
